<template>
  <div class="app-container">
    <div class="filter-container">
      <el-button type="primary" @click="handleCreate">水果入库</el-button>
    </div>

    <el-table
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="name" label="水果名称" />
      <el-table-column prop="day" label="日期" />
      <el-table-column prop="jinhuo" label="进货地" />
      <el-table-column prop="kucun" label="库存" />
      <el-table-column prop="maichu" label="卖出" />
      <el-table-column prop="price" label="价格" />
      <el-table-column prop="shouyi" label="收益" />
      <el-table-column label="操作" width="250">
        <template #default="{row}">
          <el-button size="mini" @click="handleUpdate(row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">删除</el-button>
          <el-button size="mini" type="primary" @click="handleSell(row)">卖出</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form ref="form" :rules="rules" :model="temp" label-width="100px">
        <el-form-item label="水果名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="日期" prop="day">
          <el-date-picker
            v-model="temp.day"
            type="date"
            placeholder="选择日期"
            value-format="yyyy年MM月dd日"
            format="yyyy年MM月dd日"
          />
        </el-form-item>
        <el-form-item label="进货地" prop="jinhuo">
          <el-input v-model="temp.jinhuo" />
        </el-form-item>
        <el-form-item label="库存" prop="kucun">
          <el-input-number v-model="temp.kucun" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="卖出" prop="maichu">
          <el-input v-model="temp.maichu" :disabled="dialogStatus === 'create'" />
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input-number v-model="temp.price" :min="0" :step="1" />
        </el-form-item>
        <el-form-item label="收益" prop="shouyi">
          <el-input-number v-model="temp.shouyi" :min="0" :step="1" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { sellFruit, getGroupData, createGroupData, updateGroupData, deleteGroupData, submitMaichuRecord } from '@/api/group'

export default {
  data() {
    return {
      list: [],
      dialogVisible: false,
      dialogTitle: '',
      dialogStatus: '',
      temp: {
        id: undefined,
        name: '',
        day: '',
        jinhuo: '',
        kucun: 0,
        maichu: '',
        shouyi: ''
      },
      // 校验
      rules: {
        name: [{ required: true, message: '请输入水果名称', trigger: 'change' }],
        day: [{ required: true, message: '请选择日期', trigger: 'change' }],
        jinhuo: [{ required: true, message: '请输入进货地', trigger: 'change' }],
        kucun: [
          { required: true, message: '请输入库存数量', trigger: 'change' }

        ],
        price: [{ required: true, message: '请输入价格', trigger: 'change' }]

      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      getGroupData().then(response => {
        this.list = response.data

        console.log(this.list)
      })
    },
    handleCreate() {
      this.dialogTitle = '水果入库'
      this.dialogStatus = 'create'
      this.dialogVisible = true
      this.resetTemp()
    },
    handleUpdate(row) {
      this.dialogTitle = '编辑水果信息'
      this.dialogStatus = 'update'
      this.dialogVisible = true
      this.temp = Object.assign({}, row)
    },
    handleDelete(row) {
      deleteGroupData(row.id).then(() => {
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
        this.getList()
      })
    },
    async createData() {
      try {
        await this.$refs.form.validate()

        createGroupData(this.temp).then(() => {
          this.dialogVisible = false
          this.$message({
            type: 'success',
            message: '添加成功!'
          })
          this.getList()
        })
      } catch (error) {
        console.log(error)
      }
    },
    updateData() {
      updateGroupData(this.temp).then(() => {
        this.dialogVisible = false
        this.$message({
          type: 'success',
          message: '更新成功!'
        })
        this.getList()
      })
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        day: '',
        jinhuo: '',
        kucun: 0,
        maichu: '',
        price: 0,
        shouyi: ''
      }
    },
    // handleSell(row) {
    //   console.log(row)

    //   this.$prompt('请输入卖出数量', '卖出确认', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     inputPattern: /^[1-9]\d*$/,
    //     inputErrorMessage: '请输入有效的正整数'
    //   }).then(({ value }) => {
    //     sellProduct({ name: row.name, count: parseInt(value) }).then(() => {
    //       this.$message({
    //         type: 'success',
    //         message: `成功卖出${value}件!`
    //       })
    //       this.getList()
    //     })
    //   }).catch(() => {
    //     this.$message({
    //       type: 'info',
    //       message: '已取消卖出'
    //     })
    //   })
    // }
    handleSell(row) {
      this.$prompt('请输入卖出数量', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /^\d+$/,
        inputErrorMessage: '请输入有效数字',

        inputValidator: (value) => {
          // aaa(value)
          const sellNum = parseInt(value)
          if (sellNum > row.kucun) {
            return '仓库没有那么多货！当前库存: ' + row.kucun
          }
          return true
        }
      }).then(({ value }) => {
        const sellNum = parseInt(value)

        const aa = {
          ...row,
          maichu: row.maichu += +value,
          shouyi: row.shouyi = row.maichu * value,
          kucun: row.kucun -= +value
        }

        submitMaichuRecord(aa)

        console.log(aa, '卖出')

        // 调用卖出接口

        // 调用API接口
        sellFruit({
          id: row.id,
          sellNum: sellNum
        }).then(response => {
          this.$message.success(`卖出成功！库存剩余: ${response.data.kucun}`)
          this.getList() // 刷新表格数据
        }).catch(error => {
          if (error.code === 60205) {
            this.$message.error('库存不足，无法卖出')
          } else {
            this.$message.error(error.message || '卖出失败')
          }
        })
      }).catch(() => {
        this.$message.info('已取消卖出')
      })
    }
  }
  // aaa(row, value) {
  //   row.maichu += value
  // }

}
</script>

<style scoped>
.filter-container {
  margin-bottom: 20px;
}
</style>

// 在mock/user.js中也需要更新销售逻辑
